package com.scmagic.flutter_atauth

import android.content.Context
import android.util.TypedValue
import android.widget.RelativeLayout
import android.widget.TextView
import android.widget.Toast
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.PluginRegistry.Registrar
import com.mobile.auth.gatewayauth.model.TokenRet
import com.alibaba.fastjson.JSON
import com.mobile.auth.gatewayauth.*
import com.mobile.auth.gatewayauth.model.InitResult
import io.flutter.BuildConfig
import io.flutter.plugin.common.BasicMessageChannel


class ATAuthHandler : TokenResultListener {

    private var _authHelper: PhoneNumberAuthHelper? = null
    private var _registrar: Registrar? = null
    private var _platform: BasicMessageChannel<String>? = null
    private var mDynamicView: TextView? = null;

    fun setRegister(registrar: Registrar) {
      this._registrar = registrar
      (this._registrar?.activity())?.runOnUiThread {
        /// 1. 获取授权实例
        this._authHelper = PhoneNumberAuthHelper.getInstance(this._registrar?.activeContext(), this)
        /// 2. 设置调试模式
        this._authHelper?.setDebugMode(BuildConfig.DEBUG)
        /// 3. 检查是否可以授权登录
        var result: InitResult? =  this._authHelper?.checkAuthEnvEnable()
        if(result?.isCan4GAuth == true) {
          /// 4. 设置授权页面
          this._authHelper?.setAuthUIConfig(AuthUIConfig.Builder()
            .setAppPrivacyOne("手机号码授权认证协议", "https://www.aliyun.com/product/dypns")
            .setLogoImgPath("ic_launcher")
            .setPrivacyState(true)
            .setCheckboxHidden(true)
            .create())
        }
        print(result)
      }
    }

    fun setPlatform(platform: BasicMessageChannel<String>) {
      _platform = platform
    }


    private fun sendMsg(msg: String?) {
      var activity = this._registrar?.activity();
      if(activity!=null) {
        activity.runOnUiThread {
          _platform?.send(msg)
        }
      }
    }

    override fun onTokenFailed(ret: String?) {
      (_registrar?.activity())?.runOnUiThread {
        val tokenRet = JSON.parseObject(ret, TokenRet::class.java)
        var context: Context? = this._registrar?.activeContext()
        if (tokenRet != null) {
          if(context!=null) {
            Toast.makeText(context, tokenRet.msg, Toast.LENGTH_LONG).show()
          }
          /// 接收失败
          sendMsg(ret)
        }
      }
    }

    override fun onTokenSuccess(ret: String?) {
        (_registrar?.activity())?.runOnUiThread {
          val tokenRet = JSON.parseObject(ret, TokenRet::class.java)
          var context: Context? = this._registrar?.activeContext()
          if (tokenRet != null) {
            /// 提示消息
            if(context!=null) {
              Toast.makeText(context, tokenRet.msg, Toast.LENGTH_LONG).show()
            }
            /// 发送消息给dart
            sendMsg(ret)
            if (ret?.contains("8000") == true) {
              /// 授权成功
              this._authHelper?.quitAuthActivity()
            }
          }
        }
    }

    fun checkAuthEnvEnable(call: MethodCall, result: MethodChannel.Result) {
      var initResult = this._authHelper?.checkAuthEnvEnable()
      var isCan4GAuth: Boolean? = initResult?.isCan4GAuth();
      result.success(
        isCan4GAuth
      )
    }


    fun setDebugMode(call: MethodCall, result: MethodChannel.Result) {
      var debugMode: Boolean? = call.argument<Boolean>("debugMode")
      if(debugMode != null) {
        this._authHelper?.setDebugMode(debugMode)
      }
    }

    fun preLogin(call: MethodCall, result: MethodChannel.Result) {
      var overdueTime: Int? = call.argument<Int>("overdueTime")
      if(overdueTime != null) {
        this._authHelper?.preLogin(overdueTime, object : PreLoginResultListener {
          override fun onTokenFailed(p0: String?, p1: String?) {
            result.error(p0, p1, mapOf(
              "overdueTime" to overdueTime,
              "p0" to p0,
              "p1" to p1
            ))
          }
          override fun onTokenSuccess(p0: String?) {
            result.success(mapOf(
              "result" to p0,
              "overdueTime" to overdueTime
            ))
          }
        })
      }
    }
//
//  fun dp2px(context: Context?, dipValue: Float): Int {
//    try {
//      val scale = context?.resources?.displayMetrics?.density
//      if(scale!=null)
//        return (dipValue * scale + 0.5f).toInt()
//      return dipValue.toInt()
//    } catch (e: Exception) {
//      return dipValue.toInt()
//    }
//  }
//
//
//  private fun initDynamicView() {
//    mDynamicView = TextView(_registrar?.activeContext())
//    val layoutParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
//    layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE)
//    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE)
//    layoutParams.setMargins(0, dp2px(_registrar?.context(), 450f), 0, 0)
//
//    mDynamicView?.text = "-----  自定义view  -----";
//
//    mDynamicView?.setTextColor(-0x666667)
//    mDynamicView?.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13.0f)
//    mDynamicView?.layoutParams = layoutParams
//  }

  fun getLoginToken(call: MethodCall, result: MethodChannel.Result) {
    (this._registrar?.activity())?.runOnUiThread {
      var timeout: Int? = call.argument<Int>("timeout")
      if (timeout != null) {
//        initDynamicView()
        this._authHelper?.addAuthRegistViewConfig("my_tv", AuthRegisterViewConfig.Builder().build())
        this._authHelper?.getLoginToken(timeout)
      }
      result.success(null)
    }
  }


  fun getLoginAuth(call: MethodCall, result: MethodChannel.Result) {
    (this._registrar?.activity())?.runOnUiThread {
      var timeout: Int? = call.argument<Int>("timeout")
      if (timeout != null) {
        this._authHelper?.getLoginToken(timeout)
      }
      result.success(null)
    }
  }


  fun quitAuthActivity(call: MethodCall, result: MethodChannel.Result) {
    this._authHelper?.quitAuthActivity()
    result.success(null)
  }

  fun hideLoginLoading(call: MethodCall, result: MethodChannel.Result) {
    this._authHelper?.hideLoginLoading()
    result.success(null)
  }

  companion object {
    var CheckAuthEnvEnable = "checkAuthEnvEnable"
    var SetDebugMode = "setDebugMode"
    var PreLogin = "preLogin"
    var GetLoginToken = "getLoginToken"
    var QuitAuthActivity = "quitAuthActivity"
    var HideLoginLoading = "hideLoginLoading"
  }
}